package com.company.cloud.product.client;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.data.bean.DataQueryRuleItem;

public abstract class QueryModel<T> {

	public abstract QueryWrapper<T> customQueryWrapperItem(QueryWrapper<T> queryWrapper, DataQueryRuleItem item);

	public QueryWrapper<T> getQueryWrapper(List<DataQueryRuleItem> items, Set<String> customNames) {
		if (CollectionUtils.isEmpty(customNames)) {
			customNames = new HashSet<String>();
		}
		QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
		for (DataQueryRuleItem item : items) {
			if (customNames.contains(item.getName())) {
				queryWrapper = this.customQueryWrapperItem(queryWrapper, item);
			} else {
				queryWrapper = this.queryWrapperItem(queryWrapper, item);
			}
		}
		return queryWrapper;
	}

	private QueryWrapper<T> queryWrapperItem(QueryWrapper<T> queryWrapper, DataQueryRuleItem item) {
		if (item.getVal()!=null) {
			return this.queryWrapperItem(queryWrapper, item.getName(),item.getOp(),item.getVal());
		} else if (!CollectionUtils.isEmpty(item.getVals())) {
			return this.queryWrapperItem(queryWrapper, item.getName(), item.getOp(), item.getVals());
		} else {
			return queryWrapper;
		}
	}

	private QueryWrapper<T> queryWrapperItem(QueryWrapper<T> queryWrapper, String name, String op, Object val) {
			if("eq".equals(op)) {
				return queryWrapper.eq(name, val);
			}
			return queryWrapper;
	}

	private QueryWrapper<T> queryWrapperItem(QueryWrapper<T> queryWrapper, String name, String op, List<Object> vals) {
		if("in".equals(op)) {
			return queryWrapper.in(name, vals);
		}
		return queryWrapper;
	}

}
